<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生成绩管理系统</title>
  <style>
    /* 全局样式重置与基础设置 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      padding: 20px;
    }

    h2 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
    }

    /* 表单区域样式 */
    .form-container {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-group label {
      display: block;
      margin-bottom: 5px;
      color: #666;
    }

    .form-group input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
      outline: none;
    }

    .form-group input:focus {
      border-color: #007bff;
    }

    .error {
      color: red;
      font-size: 12px;
      margin-top: 3px;
      display: none;
    }

    .btn-add {
      background-color: #007bff;
      color: white;
      padding: 8px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .btn-add:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }

    /* 排序按钮区域样式 */
    .sort-buttons {
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 8px;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    .sort-buttons button {
      margin-right: 10px;
      padding: 6px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      background-color: #f9f9f9;
      cursor: pointer;
    }

    .sort-buttons button.active {
      background-color: #007bff;
      color: white;
      border-color: #007bff;
    }

    /* 学生列表区域样式，设置固定高度和滚动 */
    .student-list {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      max-height: 300px; /* 设置最大高度，超出则滚动 */
      overflow-y: auto;
    }

    .student-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #eee;
    }

    .student-item span {
      margin-right: 15px;
    }

    .student-name {
      color: #007bff;
      cursor: pointer;
      font-weight: bold;
    }

    .btn-delete {
      background-color: #dc3545;
      color: white;
      padding: 4px 8px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    /* 详情弹窗样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 400px;
      border-radius: 8px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    .modal-header {
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    .modal-body {
      padding: 15px 0;
    }

    .modal-body p {
      margin-bottom: 10px;
    }

    .modal-footer {
      padding-top: 10px;
      border-top: 1px solid #eee;
      text-align: right;
    }

    .btn-close {
      background-color: #007bff;
      color: white;
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    /* 成绩等级样式 */
    .grade {
      font-weight: bold;
      padding: 2px 5px;
      border-radius: 3px;
    }

    .grade-a { background-color: #d4edda; color: #155724; }
    .grade-b { background-color: #cce5ff; color: #004085; }
    .grade-c { background-color: #fff3cd; color: #856404; }
    .grade-d { background-color: #ffeeba; color: #856404; }
    .grade-f { background-color: #f8d7da; color: #721c24; }
  </style>
</head>

<body>
  <h2>学生成绩管理系统</h2>
  <!-- 表单区域 -->
  <div class="form-container">
    <div class="form-group">
      <label for="name">姓名</label>
      <input type="text" id="name" placeholder="请输入姓名">
      <div class="error" id="nameError">姓名不能为空</div>
    </div>
    <div class="form-group">
      <label for="math">数学成绩</label>
      <input type="number" id="math" placeholder="请输入数学成绩（0-100）">
      <div class="error" id="mathError">数学成绩需为0-100的有效数字</div>
    </div>
    <div class="form-group">
      <label for="english">英语成绩</label>
      <input type="number" id="english" placeholder="请输入英语成绩（0-100）">
      <div class="error" id="englishError">英语成绩需为0-100的有效数字</div>
    </div>
    <button class="btn-add" id="addStudentBtn" onclick="addStudent()" disabled>添加学生</button>
  </div>

  <!-- 排序按钮区域 -->
  <div class="sort-buttons">
    <button onclick="sortStudents('id')" class="active">按ID排序</button>
    <button onclick="sortStudents('name')">按姓名排序</button>
    <button onclick="sortStudents('math')">按数学排序</button>
    <button onclick="sortStudents('english')">按英语排序</button>
    <button onclick="sortStudents('average')">按平均分排序</button>
  </div>

  <!-- 学生列表区域，可滚动 -->
  <div class="student-list" id="studentList">
    <!-- 学生信息会动态渲染到这里 -->
  </div>

  <!-- 学生详情弹窗 -->
  <div id="studentModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="modalTitle">学生详情</h2>
        <span class="close" onclick="closeModal()">&times;</span>
      </div>
      <div class="modal-body">
        <p><strong>姓名:</strong> <span id="modalName"></span></p>
        <p><strong>ID:</strong> <span id="modalId"></span></p>
        <p><strong>数学成绩:</strong> <span id="modalMath"></span></p>
        <p><strong>英语成绩:</strong> <span id="modalEnglish"></span></p>
        <p><strong>平均分:</strong> <span id="modalAverage"></span></p>
        <p><strong>成绩等级:</strong> <span id="modalGrade" class="grade"></span></p>
      </div>
      <div class="modal-footer">
        <button class="btn-close" onclick="closeModal()">关闭</button>
      </div>
    </div>
  </div>

  <script>
    let students = [
      { id: 1, name: "张三", math: 90, english: 85 },
      { id: 2, name: "李四", math: 78, english: 92 },
      { id: 3, name: "王五", math: 65, english: 70 },
      { id: 4, name: "赵六", math: 88, english: 80 },
      { id: 5, name: "钱七", math: 95, english: 91 },
      { id: 6, name: "孙八", math: 72, english: 78 },
      { id: 7, name: "周九", math: 60, english: 65 },
      { id: 8, name: "吴十", math: 82, english: 87 },
      { id: 9, name: "郑十一", math: 76, english: 74 },
      { id: 10, name: "王十二", math: 89, english: 83 }
    ];
    let sortField = 'id'; // 默认按ID排序
    let sortDirection = 'asc'; // 默认升序

    // 表单验证相关变量
    let nameValid = false, mathValid = false, englishValid = false;

    // 页面加载完成后渲染学生列表
    window.onload = function () {
      renderStudentList();
      // 给输入框绑定失去焦点事件，实时验证
      document.getElementById('name').addEventListener('blur', validateName);
      document.getElementById('math').addEventListener('blur', validateMath);
      document.getElementById('english').addEventListener('blur', validateEnglish);
    };

    // 渲染学生列表函数
    function renderStudentList() {
      const studentList = document.getElementById('studentList');
      studentList.innerHTML = '';
      students.forEach(student => {
        const average = (student.math + student.english) / 2;
        const item = document.createElement('div');
        item.className = 'student-item';
        item.innerHTML = `
          <div>
            <span>ID: ${student.id}</span>
            <span class="student-name" onclick="showStudentDetails(${student.id})">姓名: ${student.name}</span>
            <span>数学: ${student.math}</span>
            <span>英语: ${student.english}</span>
            <span>平均分: ${average.toFixed(2)}</span>
          </div>
          <button class="btn-delete" onclick="deleteStudent(${student.id})">删除</button>
        `;
        studentList.appendChild(item);
      });
    }

    // 添加学生函数
    function addStudent() {
      const name = document.getElementById('name').value.trim();
      const math = parseInt(document.getElementById('math').value);
      const english = parseInt(document.getElementById('english').value);

      const newId = students.length > 0 ? students[students.length - 1].id + 1 : 1;
      students.push({ id: newId, name, math, english });
      renderStudentList();

      // 清空输入框
      document.getElementById('name').value = '';
      document.getElementById('math').value = '';
      document.getElementById('english').value = '';
      // 重置验证状态
      nameValid = mathValid = englishValid = false;
      document.getElementById('addStudentBtn').disabled = true;
      // 隐藏错误提示
      document.getElementById('nameError').style.display = 'none';
      document.getElementById('mathError').style.display = 'none';
      document.getElementById('englishError').style.display = 'none';
    }

    // 删除学生函数
    function deleteStudent(id) {
      if (confirm('确定删除该学生吗？')) {
        students = students.filter(student => student.id !== id);
        renderStudentList();
      }
    }

    // 排序学生函数
    function sortStudents(field) {
      // 如果点击的是当前排序字段，切换排序方向
      if (sortField === field) {
        sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        sortField = field;
        // 成绩相关字段默认降序排序
        sortDirection = ['math', 'english', 'average'].includes(field) ? 'desc' : 'asc';
      }

      // 更新排序按钮的选中状态
      const sortButtons = document.querySelectorAll('.sort-buttons button');
      sortButtons.forEach(btn => {
        btn.classList.remove('active');
        if (btn.onclick.toString().includes(`sortStudents('${field}')`)) {
          btn.classList.add('active');
        }
      });

      students.sort((a, b) => {
        let valueA, valueB;
        if (field === 'average') {
          valueA = (a.math + a.english) / 2;
          valueB = (b.math + b.english) / 2;
        } else if (field === 'name') {
          valueA = a.name.toLowerCase();
          valueB = b.name.toLowerCase();
          return sortDirection === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
        } else {
          valueA = a[field];
          valueB = b[field];
        }
        return sortDirection === 'asc' ? valueA - valueB : valueB - valueA;
      });

      renderStudentList();
    }

    // 姓名验证函数
    function validateName() {
      const name = document.getElementById('name').value.trim();
      const error = document.getElementById('nameError');
      if (name === '') {
        error.style.display = 'block';
        nameValid = false;
      } else {
        error.style.display = 'none';
        nameValid = true;
      }
      checkFormValid();
    }

    // 数学成绩验证函数
    function validateMath() {
      const math = document.getElementById('math').value;
      const error = document.getElementById('mathError');
      if (isNaN(math) || math < 0 || math > 100) {
        error.style.display = 'block';
        mathValid = false;
      } else {
        error.style.display = 'none';
        mathValid = true;
      }
      checkFormValid();
    }

    // 英语成绩验证函数
    function validateEnglish() {
      const english = document.getElementById('english').value;
      const error = document.getElementById('englishError');
      if (isNaN(english) || english < 0 || english > 100) {
        error.style.display = 'block';
        englishValid = false;
      } else {
        error.style.display = 'none';
        englishValid = true;
      }
      checkFormValid();
    }

    // 检查表单是否整体有效，决定"添加学生"按钮是否可用
    function checkFormValid() {
      const addBtn = document.getElementById('addStudentBtn');
      if (nameValid && mathValid && englishValid) {
        addBtn.disabled = false;
      } else {
        addBtn.disabled = true;
      }
    }

    // 显示学生详情函数
    function showStudentDetails(id) {
      const student = students.find(s => s.id === id);
      if (!student) return;

      const average = (student.math + student.english) / 2;
      const grade = getGrade(average);

      document.getElementById('modalId').textContent = student.id;
      document.getElementById('modalName').textContent = student.name;
      document.getElementById('modalMath').textContent = student.math;
      document.getElementById('modalEnglish').textContent = student.english;
      document.getElementById('modalAverage').textContent = average.toFixed(2);
      document.getElementById('modalGrade').textContent = grade;
      document.getElementById('modalGrade').className = `grade grade-${grade.toLowerCase()}`;

      document.getElementById('studentModal').style.display = 'block';
    }

    // 关闭模态框函数
    function closeModal() {
      document.getElementById('studentModal').style.display = 'none';
    }

    // 获取成绩等级函数
    function getGrade(average) {
      if (average >= 90) return 'A';
      if (average >= 80) return 'B';
      if (average >= 70) return 'C';
      if (average >= 60) return 'D';
      return 'F';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
      const modal = document.getElementById('studentModal');
      if (event.target === modal) {
        closeModal();
      }
    }
  </script>
</body>

</html>
